# ~*~ coding: utf-8 ~*~
# auth: haochenxiao
import sys
import os
import time
import importlib
importlib.reload(sys)

import subprocess
import os
import logging
import sys
import datetime
from copy import deepcopy
import json
import shutil
import difflib
import redis
import requests
import subprocess

from django.core import serializers
import paramiko
from django.db.models import Q
from django.shortcuts import render, redirect
from django.views.generic import ListView, TemplateView, View, DetailView
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.http import FileResponse


from django.shortcuts import render_to_response,HttpResponse
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import authenticate,login
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.db import connection
from django import forms
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User, Group, Permission
import configparser
from devops.auth import check
from devops.ansible_api import *
from devops.models import AutoReCovery,MonitorConfig,ChartHistory,Prometheus
from resources.models import NewServer,ServerUser,ServerGroup
from users.models import Profile
from devops.ansible_api import *
from alert.models import LinkGroup,LinkPerson
from confs.views import get_pagerange
#日志文件配置
from confs.Log import logger

#定时任务调度
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job
scheduler = BackgroundScheduler()
scheduler.add_jobstore(DjangoJobStore(), "default")
#日志打印
#scheduler._logger = logger

from devops.monitor_items import web_monitor,check_port,web_monitor_test,check_port_test,devicemsg,process_status
from confs.Configs import *
from devops.prometheus_client import PrometheusClient

#时间对应关系
v_frequency = {0:5,1:10,2:30,3:60,4:180,5:300}
mysql_frequency = {0:10,1:60,2:300}
oracle_frequency = {0:1,1:24}
#v_frequency = {0:5,1:10,2:15,3:30,4:60}



def AddMysqlJob(func,frequency,name,args):
	# seconds minutes
	times = mysql_frequency[frequency]
	scheduler.add_job(func, trigger='interval', id=name, seconds=times, args=args,coalesce=True,
					  replace_existing=True,max_instances=100)

def AddOracleJob(func,frequency,name,args):
	# seconds minutes hours
	times = oracle_frequency[frequency]
	scheduler.add_job(func, trigger='interval', id=name, hours=times, args=args,coalesce=True,
					  replace_existing=True,max_instances=100)

def AddJob(func,frequency,name,args):
	# seconds minutes
	times = v_frequency[int(frequency)]
	scheduler.add_job(func, trigger='interval', id=name, seconds=times, args=args, coalesce=True,
					  replace_existing=True,max_instances=100)

def AddHostJob(func,frequency,name,args):
	# seconds minutes
	scheduler.add_job(func, trigger='interval', id=name, minutes=1, args=args, coalesce=True,
					  replace_existing=True,max_instances=100)

def ModifyJob(name,args):
	scheduler.modify_job(job_id=name,args=args)

def StopJob(id):
	scheduler.pause_job(job_id=id)

def ReStart(id):
	scheduler.resume_job(id)

def ReMove(id):
	try:
		StopJob(id)
	except Exception as e:
		print ('error is ',e)
	scheduler.remove_job(id)
	#删除所有定时任务
	#scheduler.remove_all_job()

class APIAutoRecoveryView(LoginRequiredMixin, ListView):
	def get(self,request):
		jsondata = {
			"code": 0,
			"msg": "",
			"count": 10,
			"data": [
			]
		}
		atr = AutoReCovery.objects.all()
		for s in atr:
			m = {"id": s.id,"item":s.item,"action":s.action,"status":s.status}
			jsondata["data"].append(m)

		return JsonResponse(jsondata)


class APIPrometheusView(LoginRequiredMixin, ListView):
	def get(self,request):
		jsondata = {
			"code": 0,
			"msg": "",
			"count": 10,
			"data": [
			]
		}
		atr = Prometheus.objects.all()
		for s in atr:
			m = {"id": s.id,"item":s.item,"action":s.action,"type": s.type,"level":s.level,"port":s.port,"switch":s.switch,"status":s.status}
			jsondata["data"].append(m)
		#m = {"id": 1,"item":'test',"action":'rtes',"type": 'test',"level":'test',"port":'333',"switch":True}
		#jsondata["data"].append(m)
		#print ('jsondata is ',jsondata)
		return JsonResponse(jsondata)


class AutoRecoveryView(LoginRequiredMixin, ListView):
	template_name = 'autorecovery.html'
	model = AutoReCovery
	paginate_by = 10
	ordering = 'id'

	def get_context_data(self, **kwargs):
		context = super(AutoRecoveryView, self).get_context_data(**kwargs)
		context['page_range'] = get_pagerange(context['page_obj'])
		return context

	def post(self,request):
		ret = {'status': 0}
		item = request.POST.get('item')
		#alertime = request.POST.get('alertime')
		#fixtime = request.POST.get('fixtime')
		action = request.POST.get('action')

		if item in [ m.item for m in  AutoReCovery.objects.all() ]:
			ret['status'] = 1
			ret['msg'] = '自愈项名称已存在,请重新填写'
			return JsonResponse(ret)


		AutoReCovery.objects.create(item=item,action=action)
		ret['msg'] = '自动推送完成'

		return JsonResponse(ret)



class PrometheusView(LoginRequiredMixin, ListView):
	template_name = 'prometheus.html'
	model = Prometheus
	paginate_by = 10
	ordering = 'id'

	def get_context_data(self, **kwargs):
		context = super(PrometheusView, self).get_context_data(**kwargs)
		context['page_range'] = get_pagerange(context['page_obj'])
		return context

	def post(self,request):
		ret = {'status': 0}
		item = request.POST.get('item')
		type = request.POST.get('type')
		level = request.POST.get('level')
		port = request.POST.get('port')
		action = request.POST.get('action')
		switch = request.POST.get('switch')
		status = request.POST.get('status')
		if switch == None:
			switch = 'off'
		if item in [ m.item for m in  Prometheus.objects.all() ]:
			ret['status'] = 1
			ret['msg'] = '自愈项名称已存在,请重新填写'
			return JsonResponse(ret)


		Prometheus.objects.create(item=item,type=type,level=level,port=port,action=action,switch=switch,status=status)
		ret['msg'] = '自动推送完成'

		return JsonResponse(ret)


class AutoRecoveryEditView(LoginRequiredMixin, TemplateView):
	template_name = 'autorecovery_edit.html'

	def get(self, request):
		id = request.GET.get('id')
		acy = AutoReCovery.objects.get(id=id)
		jsondata = {"id":acy.id,"item":acy.item,"action":acy.action}
		return JsonResponse(jsondata)

	def post(self,request):
		ret = {'status': 0}
		item = request.POST.get('item')
		alertime = request.POST.get('alertime')
		fixtime = request.POST.get('fixtime')
		action = request.POST.get('action')

		try:
			acy = AutoReCovery.objects.get(item=item)
			acy.alertime = alertime
			acy.fixtime = fixtime
			acy.action = action
			acy.save()

			ret['msg'] = '自动推送完成'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return HttpResponseRedirect('/devops/autorecovery/')


class PrometheusEditView(LoginRequiredMixin, TemplateView):
	template_name = 'autorecovery_edit.html'

	def get(self, request):
		id = request.GET.get('id')
		s = Prometheus.objects.get(id=id)
		jsondata = {"id": s.id,"item":s.item,"action":s.action,"type": s.type,"level":s.level,"port":s.port,"switch":s.switch,"status":s.status}
		return JsonResponse(jsondata)

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('id')
		item = request.POST.get('item')
		type = request.POST.get('type')
		level = request.POST.get('level')
		port = request.POST.get('port')
		#action = request.POST.get('action')
		switch = request.POST.get('switch')
		status = request.POST.get('status')
		print ('item is ',item)
		try:
			acy = Prometheus.objects.get(id=id)
			acy.item = item
			acy.type = type
			acy.level = level
			acy.port = port
			#acy.action = action
			acy.switch = switch
			acy.status = status
			acy.save()

			ret['msg'] = '自动推送完成'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return HttpResponseRedirect('/devops/prometheus/')


class AutoRecoveryDeleteView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('autorecovery_id')
		try:
			arc = AutoReCovery.objects.get(id=id)
			arc.delete()
			ret['msg'] = '删除成功'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return JsonResponse(ret)

class PrometheusDeleteView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('prometheus_id')
		try:
			arc = Prometheus.objects.get(id=id)
			arc.delete()
			ret['msg'] = '删除成功'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return JsonResponse(ret)

class AutoRecoveryStartView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('autorecovery_id')
		try:
			arc = AutoReCovery.objects.get(id=id)
			arc.status = 1
			arc.save()
			ret['msg'] = '启用成功'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return JsonResponse(ret)

class AutoRecoveryStopView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('autorecovery_id')
		try:
			arc = AutoReCovery.objects.get(id=id)
			arc.status = 0
			arc.save()
			ret['msg'] = '禁用成功'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return JsonResponse(ret)

class PrometheusStartView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('prometheus_id')
		try:
			arc = Prometheus.objects.get(id=id)
			arc.switch = 'on'
			arc.save()
			ret['msg'] = '启用成功'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return JsonResponse(ret)

class PrometheusStopView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('prometheus_id')
		try:
			arc = Prometheus.objects.get(id=id)
			arc.switch = 'off'
			arc.save()
			ret['msg'] = '禁用成功'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return JsonResponse(ret)


class APIMonitorConfigView(LoginRequiredMixin, ListView):
	def get(self,request):
		jsondata = {
			"code": 0,
			"msg": "",
			"count": 10,
			"data": [
			]
		}
		atr = MonitorConfig.objects.all()
		for s in atr:
			#反查
			item = ','.join([x.item for x in s.mc.all()])
			alert = ','.join([x.item for x in s.mc.all()])
			m = {"id": s.id,"name":s.name,"type":s.type,"url":s.url,"address":s.address,"port":s.port,"process_name":s.process_name,
				 "frequency":s.frequency,"item":item,"alert":alert,"alert_type":s.alert_type,"status":s.status,"auto_status":s.auto_status,
				 "utime":s.utime}

			jsondata["data"].append(m)

		return JsonResponse(jsondata)


class AddMonitorConfigView(LoginRequiredMixin, ListView):
	template_name = 'monitorconfig.html'
	model = MonitorConfig
	paginate_by = 10
	ordering = 'id'

	def get(self, request):

		type_list = [{"value": m[0], "name": m[1]} for m in MonitorConfig.type_list ]
		frequency_list = MonitorConfig.frequency_list
		linkgroup_list = [{"value": m.id, "name": m.name} for m in LinkGroup.objects.all()]
		alert_type_list = [{"value": m[0], "name": m[1]} for m in MonitorConfig.alert_type_list ]
		newserver_list = [{"value": m.id, "name": m.hostname} for m in NewServer.objects.all()]
		autorecovery_list = [{"value": m.id, "name": m.item} for m in AutoReCovery.objects.all()]

		jsondata = {"type_list": type_list, "frequency_list": frequency_list, "linkgroup_list": linkgroup_list,
					"alert_type_list": alert_type_list,"newserver_list":newserver_list,"autorecovery_list":autorecovery_list}
		return JsonResponse(jsondata)

class MonitorConfigView(LoginRequiredMixin, ListView):
	template_name = 'monitorconfig.html'
	model = MonitorConfig
	paginate_by = 10
	ordering = 'id'

	def get(self, request):
		return render_to_response('monitorconfig.html', locals())


	def post(self,request):
		ret = {'status': 0}
		name = request.POST.get('name')
		type = request.POST.get('type')
		url = request.POST.get('url','')
		frequency = request.POST.get('frequency','')
		remarks = request.POST.get('remarks')
		address = request.POST.get('address','')
		port = request.POST.get('port',0)
		process = request.POST.get('process', '')
		process_ip = request.POST.get('process_ip', '')
		print ('ip is ',process_ip)
		#执行主机列表
		sv_ip_list = request.POST.getlist('sv_ip', [])

		#自愈项列表
		ac_id_list = request.POST.getlist('ac_id', [])
		if ac_id_list == []:
			ret['status'] = 1
			ret['msg'] = '请添加自愈项'
			return JsonResponse(ret)


		item = ac_id_list
		#告警
		linkgroup_id = request.POST.get('linkgroup_id', '')
		if linkgroup_id == '':
			ret['status'] = 1
			ret['msg'] = '请添加联系人组'
			return JsonResponse(ret)

		linkgroup = LinkGroup.objects.get(id=linkgroup_id)
		linkgroup_num = len(linkgroup.gl.all())
		if linkgroup_num == 0:
			ret['status'] = 1
			ret['msg'] = '请在联系人组中添加成员'
			return JsonResponse(ret)


		alert_type = request.POST.get('alert_type',1)


		#默认启用监控
		status = 1
		#v_frequency = {0:1,1:5,2:15,3:30,4:60}


		# 删除所有定时任务
		#scheduler.remove_all_jobs()
		#ret['status'] = 1
		#ret['msg'] = 'test'

		#站点监控
		if int(type) == 0:
			try:
				status_code = web_monitor_test(url)

				if status_code < 400:
					ret['status'] = 0
					# 添加定时任务
					AddJob(web_monitor, frequency, name, [url,name,item,sv_ip_list])
				else:
					ret['status'] = 1
					ret['msg'] = '返回状态码大于等于400,请查找原因'
			except Exception as e:
				logger.info(e)
				ret['status'] = 1
				ret['msg'] = str(e)
				return JsonResponse(ret)
		
		#端口监控
		if int(type) == 1:
			try:
				port_status = check_port_test(address,port)
				if port_status == 0:
					ret['status'] = 0
					AddJob(check_port, frequency, name, [address,port,name,item,sv_ip_list])
				else:
					ret['status'] = 1
					ret['msg'] = '测试连接失败,请查找原因'
					return JsonResponse(ret)

			except Exception as e:
				logger.info(e)
				ret['status'] = 1
				ret['msg'] = str(e)
				return JsonResponse(ret)

		# 进程监控
		if int(type) == 2:
			try:
				check_status = process_status(process_ip,process,name,item,0,sv_ip_list)
				if check_status != 0:
					ret['status'] = 0
					AddJob(process_status, frequency, name, [process_ip,process,name,item,1,sv_ip_list])
				else:
					ret['status'] = 1
					ret['msg'] = '测试进程名称不存在,请检查后重试'
					return JsonResponse(ret)

			except Exception as e:
				logger.info(e)
				ret['status'] = 1
				ret['msg'] = str(e)
				return JsonResponse(ret)

		try:
			sv_ip_list = json.dumps(sv_ip_list)
			mcf = MonitorConfig.objects.create(name=name,type=type,url=url,frequency=frequency,remarks=remarks,status=status, \
										  address=address,port=port,alert_status=2,alert_type=alert_type,sv_ip=sv_ip_list,process_name=process)
			# 多对多添加
			#添加自愈项

			for ac_id in ac_id_list:
				at_mc = AutoReCovery.objects.get(pk=ac_id)
				mcf.mc.add(at_mc)
			#添加联系人组
			mcf.ml.add(linkgroup)
			mcf.save()


			ret['msg'] = '自动推送完成'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)

		return JsonResponse(ret)


class MonitorConfigDeleteView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('monitorconfig_id')
		try:
			arc = MonitorConfig.objects.get(id=id)
			if arc.name:
				scheduler.remove_job(arc.name)
				arc.delete()
				ret['msg'] = '删除成功'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return JsonResponse(ret)

class MonitorConfigStopView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('monitorconfig_id')
		try:
			arc = MonitorConfig.objects.get(id=id)
			scheduler.pause_job(arc.name)
			arc.status = 0
			arc.save()
			ret['msg'] = '禁用成功'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return JsonResponse(ret)

class MonitorConfigStartView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('monitorconfig_id')
		try:
			arc = MonitorConfig.objects.get(id=id)
			scheduler.resume_job(arc.name)
			arc.status = 1
			arc.save()
			ret['msg'] = '启用成功'
		except Exception as e:
			logger.info(e)
			ret['status'] = 1
			ret['msg'] = str(e)
		return JsonResponse(ret)

class MonitorConfigEditView(LoginRequiredMixin, TemplateView):
	template_name = 'monitorconfig_edit.html'

	def get(self, request):
		id = request.GET.get('id')
		mcf = MonitorConfig.objects.get(id=id)
		lg_objs = LinkGroup.objects.all()
		alert_type_list = MonitorConfig.alert_type_list

		#告警组
		linkgroup_list = []
		lglist = [x.id for x in mcf.ml.all() ]
		for s in lg_objs:
			if s.id in lglist:
				linkgroup_list.append({"name": s.name, "value": s.id, "selected": True})
			else:
				linkgroup_list.append({"name": s.name, "value": s.id})

		#告警方式
		allist = []
		for l in alert_type_list:
			if mcf.alert_type == l[0]:
				allist.append({"name": l[1], "value": l[0], "selected": True})
			else:
				allist.append({"name": l[1], "value": l[0]})

		#告警状态
		auto_status_list = []
		if mcf.auto_status:
			auto_status_list.append({"name": "正常状态", "value": 1, "selected": True})
			auto_status_list.append({"name": "维护状态", "value": 0})
		else:
			auto_status_list.append({"name": "正常状态", "value": 1})
			auto_status_list.append({"name": "维护状态", "value": 0, "selected": True})

		jsondata = {"id": mcf.id, "name": mcf.name, "linkgroup_list":linkgroup_list,"allist":allist,
					"auto_status":auto_status_list}

		return JsonResponse(jsondata)




	def post(self,request):
		ret = {'status': 0}
		name = request.POST.get('name')
		#ar_id = request.POST.getlist('ar_id')[0]
		linkgroup_id = request.POST.get('linkgroup_id')
		alert_type = request.POST.get('alert_type')
		auto_status = request.POST.get('auto_status')
		mcf = MonitorConfig.objects.get(name=name)
		type = mcf.type
		mcf.auto_status = auto_status
		mcf.alert_type = alert_type
		#arc = AutoReCovery.objects.get(id=ar_id)
		#mcf.mc.clear()
		#mcf.mc.add(arc)
		lg_obj = LinkGroup.objects.get(id=linkgroup_id)
		mcf.ml.clear()
		mcf.ml.add(lg_obj)
		mcf.save()

		ret['msg'] = '自动推送完成'

		return JsonResponse(ret)

class ChartListView(LoginRequiredMixin, ListView):
	template_name = 'chartlist.html'
	model = NewServer
	paginate_by = 10
	ordering = 'id'

	def get(self, request):
		return render_to_response('chartlist.html', locals())

class APIChartView(LoginRequiredMixin, ListView):

	def get(self,request):
		jsondata = {
			"code": 0,
			"msg": "",
			"count": 10,
			"data": [
			]
		}
		newservers = NewServer.objects.all()
		for s in newservers:
			m = {"id": s.id,"hostname":s.hostname,"mtype":"基础监控","chart_status":s.chart_status}

			jsondata["data"].append(m)

		return JsonResponse(jsondata)

class ChartDetailView(LoginRequiredMixin, ListView):
	template_name = 'chart_detail.html'
	model = ChartHistory
	paginate_by = 10
	ordering = 'id'

	def get(self, request):
		id = request.GET.get('id')
		slice = request.GET.get('slice','')
		if slice:
			sl = int(slice)
		else:
			sl = 0
		#时间范围查找
		time_slice = ChartHistory.time_slice
		nowtime = datetime.datetime.now()

		for t in time_slice:
			if t[0] == sl:
				tn = t[2]

		if sl in range(0,5):
			delta = datetime.timedelta(hours=tn)
		else:
			delta = datetime.timedelta(days=tn)

		starttime = nowtime - delta
		endtime = nowtime

		server = NewServer.objects.get(id=id)
		hostname = server.hostname
		cpulist = []
		memlist = []
		processlist = []
		disk_root_list = {}
		disk_keys_v = {}
		color_v = {}

		# 流量
		#nflow_root_list = {}
		#nflow_keys_v = {}
		nflow_all_list = {}


		objlst = ChartHistory.objects.filter(hostid=id)
		objlist = objlst.filter(utime__range=[starttime, endtime])
		if len(objlist) == 0:
			return HttpResponse('<html><b>监控数据不存在或近期无数据,请开启监控</b></html>')
		objlist_last = objlst.filter(utime__range=[starttime, endtime]).order_by('-id')[:1][0]

		#磁盘
		disk_keys = list(json.loads(objlist_last.disk).keys())
		disk_num = len(disk_keys)
		color = ['red', 'green', 'LightPink', 'DeepPink', 'Blue', 'DoderBlue', 'Auqamarin', 'Peru'][0:disk_num]
		res_v = [ ('res'+str(disk_keys.index(x)),disk_keys.index(x)) for x in disk_keys ]
		data_v = [ ('data'+str(disk_keys.index(x))) for x in disk_keys ]

		for s in disk_keys:
			disk_keys_v['res'+str(disk_keys.index(s))] = s
		for s in color:
			color_v['res'+str(color.index(s))] = s

		#网卡流量

		# 获取网卡名称列表
		nflow_keys = list(json.loads(objlist_last.nflow).keys())
		#获取网卡查询参数名称列表
		nflow_args = ["bytesSent","bytesRecv"]

		#nflow_num = len(nflow_keys)
		#nflow_res_v = [('res' + str(nflow_keys.index(x)), nflow_keys.index(x)) for x in nflow_keys]
		#nflow_data_v = [('data' + str(nflow_keys.index(x))) for x in nflow_keys]
		#for s in nflow_keys:
		#	nflow_keys_v['res' + str(nflow_keys.index(s))] = s
		#for s in color:
		#	color_v['res' + str(color.index(s))] = s

		for net in nflow_keys:
			nflow_all_list[net] = {}
			for n in nflow_args:
				nflow_all_list[net][n] = []


		for ch in objlist:
			dtime = ch.utime
			un_time = time.mktime(dtime.timetuple())
			un_time = int(un_time)
			cpulist.append({"timeline": un_time,"value":ch.cpu})
			memlist.append({"timeline": un_time, "value": ch.mem})
			processlist.append({"timeline": un_time, "value": ch.process})
			try:
				disk_value_list = list(json.loads(ch.disk).values())
			except:
				disk_value_list = 0

			try:
				nflow_value = json.loads(ch.nflow)
			except:
				nflow_value = 0

			if ch.disk and type(disk_value_list) == list:

				for n in res_v:

					try:
						disk_root_list[n[0]].append({"timeline": un_time, "value": disk_value_list[n[1]]})
					except:
						disk_root_list[n[0]] = []
						disk_root_list[n[0]].append({"timeline": un_time, "value": disk_value_list[n[1]]})
			else:
				for n in res_v:
					try:
						disk_root_list[n[0]].append({"timeline": un_time, "value": 0})
					except:
						disk_root_list[n[0]] = []
						disk_root_list[n[0]].append({"timeline": un_time, "value": 0})

			#网卡流量
			for net in nflow_value:
				for n in nflow_args:
					try:
						#logger.info({"timeline": un_time, "value": nflow_value[net][n]})
						nflow_all_list[net][n].append({"timeline": un_time, "value": nflow_value[net][n]})
					except:
						pass


		cpulist = json.dumps(cpulist)
		memlist = json.dumps(memlist)
		processlist = json.dumps(processlist)

		#监控指标图表 CPU 内存 进程 磁盘
		ecslist = [
			(cpulist, 'main', 'CPU负载', 'red', 'CPU'),
			(memlist,'main1','内存百分比','green','内存'),
			(processlist,'main_process','进程数','yellow','进程数'),
			#(disk_root_list, 'disk', '磁盘使用率', 'plum', '磁盘目录'),
			#(nflow_root_list, 'nflow', '网卡流量', 'plum', '网卡流量')
		]

		return render_to_response('chart_detail.html', locals())

class ChartCreateView(LoginRequiredMixin, TemplateView):
	template_name = 'chart_create.html'

	def get(self, request):
		obj_servers = NewServer.objects.all()
		obj_persons = LinkPerson.objects.all()
		return render_to_response('chart_create.html', locals())

	def post(self,request):

		name = request.POST.get('name')
		dingurl = request.POST.get('dingurl')
		info = request.POST.get('info')
		memberslist = request.POST.getlist('members')
		lgp = LinkGroup.objects.create(name=name,dingurl=dingurl,info=info)

		#多对多添加
		for user_id in memberslist:
			lp = LinkPerson.objects.get(id=user_id)
			lgp.gl.add(lp)
		lgp.save()

		return HttpResponseRedirect('/alert/alert_linkgroup')

class ChartStartView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('chart_id')
		frequency = 0
		AddHostJob(devicemsg, frequency, id, [id])
		#res = devicemsg(id)

		s = NewServer.objects.get(id=id)
		s.chart_status = 1
		s.save()

		ret['msg'] = 'ok'
		return JsonResponse(ret)

class ChartStopView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		id = request.POST.get('chart_id')
		StopJob(id)
		s = NewServer.objects.get(id=id)
		s.chart_status = 0
		s.save()
		ret['msg'] = 'ok'
		return JsonResponse(ret)


class ConsoleView(LoginRequiredMixin, TemplateView):
	template_name = 'web_ssh.html'

	def get(self, request):
		id = request.GET.get('id')
		return render_to_response('web_ssh.html', locals())



	def post(self,request):

		name = request.POST.get('name')
		dingurl = request.POST.get('dingurl')
		info = request.POST.get('info')
		memberslist = request.POST.getlist('members')
		lgp = LinkGroup.objects.create(name=name,dingurl=dingurl,info=info)

		#多对多添加
		for user_id in memberslist:
			lp = LinkPerson.objects.get(id=user_id)
			lgp.gl.add(lp)
		lgp.save()

		return HttpResponseRedirect('/alert/alert_linkgroup')

def PrometheusWebhookViews(request):

	if request.method == 'POST':
		ret = {'status': 0}
		msg = request.body.decode('utf-8')
		#msg = request.body
		msg = json.loads(msg)
		msglist = msg['alerts']
		logger.info(msg)
		for m in msglist:
			try:
				status = m['status']
				alertname = m['labels']['alertname']
				severity = m['labels']['severity']
				instance = m['labels']['instance']
				port = instance.split(':')[-1]
				ip = instance.split(':')[-2].split('/')[-1]
				atn = Prometheus.objects.filter(type=alertname).filter(level=severity).filter(port=port).filter(status=status)
				if len(atn) > 0:
					logger.info(atn[0].action)
					action = atn[0].action
					switch = atn[0].switch
					if switch != 'on':
						pass
					else:
						#通过IP获取ssh信息
						datasource = 'prometheus'
						PrometheusClient(datasource,ip,action)
						logger.info('推送prometheus信息到redis')
				else:
					logger.info('prometheus告警未匹配到任何自愈规则,跳过')
			except Exception as e:
				logger.info(e)
		return JsonResponse(ret)



# 注册定时任务并开始
register_events(scheduler)
scheduler.start()